﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

namespace nExt.Web
{
	public static class WebExtensions
	{
		public static string Action<TController>(this UrlHelper urlHelper, Expression<Action<TController>> actionExpr, 
			bool returnAbsolutePath = false)
		{
			var res = new Uri(GetHelper().UrlFor(actionExpr));
			return returnAbsolutePath ? res.AbsoluteUri : res.PathAndQuery;
		}

		public static MvcHtmlString Action<TController>(this HtmlHelper htmlHelper, Expression<Func<TController, object>> actionExpr)
		{
			var helper = GetHelper();
			IDictionary<string, object> parameters;
			helper.UrlFor(actionExpr, out parameters);
			RouteValueDictionary routeValues = new RouteValueDictionary(parameters);
			return htmlHelper.Action(helper.GetActionName(actionExpr), helper.GetControllerName<TController>(), routeValues);
		}

		public static MvcHtmlString ActionLink<TController>(this HtmlHelper htmlHelper, Expression<Action<TController>> actionExpr)
		{
			string urlFor = GetHelper().UrlFor(actionExpr);
			return new MvcHtmlString(string.Format("<a href=\"{1}\" >{0}</a>", urlFor, urlFor));
		}

		public static MvcHtmlString ActionLink<TController>(this HtmlHelper htmlHelper, string linkText, Expression<Action<TController>> actionExpr)
		{
			return new MvcHtmlString(string.Format("<a href=\"{1}\" >{0}</a>", linkText, GetHelper().UrlFor(actionExpr)));
		}

		public static RedirectResult RedirectToAction<TController>(this Controller controller, Expression<Action<TController>> actionExpr)
		{
			//controller.Response.Redirect(GetHelper().UrlFor(actionExpr));
			return new RedirectResult(GetHelper().UrlFor(actionExpr));
		}

		private static Uri GetBaseUrl()
		{
			var request = HttpContext.Current.Request;
			var appUrl = HttpRuntime.AppDomainAppVirtualPath;

			var baseUrl = string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, appUrl);

			return new Uri(baseUrl);
		}

		private static RequestHelper GetHelper()
		{
			return new RequestHelper(GlobalConfiguration.Configuration, GetBaseUrl());
		}


	}
}